<template>
  <div>
    <el-container>
      <el-header style="height:auto;">
        <el-select v-model="account" clearable style="width: 20%">
          <el-option
            v-for="(item,index) in accounts"
            :key="index"
            :label="item.account + '|' + item.region"
            :value="item.id"
          />
        </el-select>
        <el-checkbox v-model="all" title="是否获取所有产品包含已经关闭广告的">所有</el-checkbox>
        <el-input
          v-model="kwInput"
          placeholder="输入关键词搜索"
          style="width: 20%"
          clearable
          class=""
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" style="width: 180px" type="success" icon="el-icon-search" @click="handleSearch">搜索
          </el-button>
        </el-input>
        <el-button type="success" @click="handleAction('create')">新增</el-button>
      </el-header>
      <el-main>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="data.filter(item => !kwInput || item.name.toLowerCase().includes(kwInput.toLowerCase()) ||item.id_product.toLowerCase().includes(kwInput.toLowerCase()))"
          border
          height="750"
          :default-sort="{prop: 'impression', order: 'descending'}"
          :summary-method="getSummaries"
          show-summary
          @sort-change="handleSort"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" style="margin-bottom: 0px">
                <el-form-item label="商品名称">
                  <span>{{ props.row.name }}</span>
                </el-form-item>
                <el-form-item label="所属店铺">
                  <span>{{ props.row.region }}</span>
                </el-form-item>
                <el-form-item label="所属账号">
                  <span>{{ props.row.account }}</span>
                </el-form-item>
                <el-form-item label="广告开始时间">
                  <span>{{ props.row.start_at }}</span>
                </el-form-item>
                <el-form-item label="产品表现">
                  <span>like:<span style="color: red;margin-right: 5px">{{ props.row.like_count }}</span></span>
                  <span>view:<span style="color: red;margin-right: 5px">{{ props.row.view_count }}</span></span>
                  <span>sold:<span style="color: red;margin-right: 5px">{{ props.row.sold }}</span></span>
                  <span>rating:<span style="color: red;margin-right: 5px">{{ props.row.rating_star.toFixed(2) }}</span></span>
                </el-form-item>
                <el-form-item label="7天表现">
                  <span><b>UV:</b><span style="color: red;margin-right: 5px">{{ props.row.uv_7days }}</span></span>
                  <span><b>CARTS:</b><span style="color: red;margin-right: 5px">{{
                    props.row.add_to_cart_buyers_7days
                  }}</span></span>
                  <span><b>LIKES:</b><span style="color: red;margin-right: 5px">{{ props.row.like_7days }}</span></span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="main_image" label="产品" width="100">
            <template slot-scope="scope">
              <a :href="scope.row.link" target="_blank"><img :src="scope.row.main_image" width="56"></a><br>
            </template>
          </el-table-column>
          <el-table-column align="center" label="售价" prop="input_promotion_price" sortable="custom" />
          <el-table-column align="center" prop="total_impression_7days" sortable="custom" label="展示">
            <template slot-scope="scope">
              <span @click="handleAdsStatics(scope.row)">{{ scope.row.total_impression_7days }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="total_click_7days" sortable="custom" label="点击" />
          <el-table-column align="center" prop="add_to_cart_buyers_7days" sortable="custom" label="cart">
            <template slot-scope="scope">
              {{ scope.row.add_to_cart_buyers_7days }}<span style="float: right;color: grey">{{
                scope.row.click > 0 ? (scope.row.add_to_cart_buyers_7days * 100 / scope.row.click).toFixed(0) : 0
              }}%</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="like_7days" sortable="custom" label="like" />
          <el-table-column align="center" prop="total_expense_7days" sortable="custom" label="cost" />
          <el-table-column align="center" prop="total_gmv_7days" sortable="custom" label="gmv">
            <template slot-scope="scope">
              <span v-if="scope.row.total_gmv_7days > 0" style="color:red"><b>{{ scope.row.total_gmv_7days }}</b></span>
              <span v-else>{{ scope.row.total_gmv_7days }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="roi" sortable="custom" label="roi">
            <template slot-scope="scope">
              <span v-if="scope.row.total_expense_7days > 0">{{ (scope.row.total_gmv_7days/scope.row.total_expense_7days).toFixed(1) }}</span>
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="running_days" label="运行" />
          <el-table-column align="center" label="id product" prop="id_product" width="110">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.campaign_status !== 1"
                round
                type="danger"
                title="查看关键词详细数据"
                size="mini"
                @click="handleShowKeywords(scope.row)"
              >
                {{ scope.row.id_product }}
              </el-button>
              <el-button
                v-else
                round
                type="success"
                title="查看关键词详细数据"
                size="mini"
                @click="handleShowKeywords(scope.row)"
              >
                {{ scope.row.id_product }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作记录" width="180">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="广告操作记录"
                width="600"
                trigger="click"
              >
                <el-table :data="scope.row.notes">
                  <el-table-column property="create_at" label="create_at" />
                  <el-table-column property="note" label="note" />
                  <el-table-column property="owner" label="owner" />
                </el-table>
                <el-button slot="reference">{{ scope.row.operation_suggest }}</el-button>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" label="更多操作" width="200">
            <template slot-scope="scope">
              <el-dropdown split-button type="primary" @click.native.stop="handleAdwordsNote(scope.row)">
                更多操作
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native.stop="handleAdwordsNote(scope.row)">添加广告记录
                  </el-dropdown-item>
                  <el-dropdown-item><a :href="scope.row.ad_link" target="_blank">打开shopee广告后台
                  </a></el-dropdown-item>
                  <el-dropdown-item divided @click.native.stop="handleAction('edit', scope.row)">修改
                  </el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleAction('delete', scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </template>
          </el-table-column>

        </el-table>

        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100,200,500]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      :title="title"
      :visible.sync="innerDialogVisible"
      width="60%"
    >
      <el-form ref="form" :model="form" label-width="160px">
        <el-form-item label="shopeeaccount">
          <el-select v-model="form.shopeeaccount_id" tyle="width: 100%" filterable clearable placeholder="选择账号区域">
            <el-option
              v-for="item in accounts"
              :key="item.id"
              :label="item.account + &quot;|&quot; + item.region"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="id_product">
          <el-input v-model="form.id_product" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="id_ads">
          <el-input v-model="form.id_ads" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="main_image">
          <el-input v-model="form.main_image" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="售价">
          <el-input v-model="form.input_promotion_price" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="采购成本">
          <el-input v-model="form.purchase_cost" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="供应商">
          <el-input v-model="form.suppliers" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="开始日期">
          <el-date-picker
            v-model="form.start_at"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="结束日期">
          <el-date-picker
            v-model="form.end_at"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </span>
    </el-dialog>
    <shopeeadskeywords
      :is-visible="shopeeadskeywordVisible"
      :shopeeadsproduct_id="shopeeadsproduct_id"
      :time_start="time_start"
      :main_image="main_image"
      :time_end="time_end"
      :ad_link="ad_link"
      @closeMyDialog="shopeeadskeywordVisible=false"
    />
    <shopeeadsoperationnote
      :shopeeadsproduct_id="shopeeadsproduct_id"
      :id_product="id_product"
      :show-dialog="shopeeadsoperationnoteVisible"
      @closeMyDialog="shopeeadsoperationnoteVisible=false"
    />

    <shopeeadsstatics
      :shopeeadsproduct_id="shopeeadsproduct_id"
      :shopee-ads-static-visuable="shopeeAdsStaticVisuable"
      @closeMyDialog="shopeeAdsStaticVisuable=false"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/shopee/shopeeadsproduct'
import { Get as GetShopeeAccount } from '@/api/shopee/shopeeaccount'
import qs from 'qs'
import Shopeeadskeywords from './element/shopeeadskeywords'
import Cookies from 'js-cookie'
import Shopeeadsoperationnote from './element/shopeeadoperationnote'
import Shopeeadsstatics from './element/shopeeAdsStatics'

const SHOPEE_ACCOUNT_ID_KEY = 'ERP_SHOPPEE_ACCOUNT_ID'

export function getCookie(key) {
  const v = Cookies.get(key)
  return v || null
}

export function setCookie(key, value) {
  return Cookies.set(key, value, { expires: 30 })
}

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  components: { Shopeeadsstatics, Shopeeadsoperationnote, Shopeeadskeywords },
  data() {
    return {
      shopeeAdsStaticVisuable: false,
      shopeeadsoperationnoteVisible: false,
      shopeeadsproduct_id: '',
      id_product: '',
      time_start: '',
      main_image: '',
      time_end: '',
      ad_link: '',
      shopeeadskeywordVisible: false,
      accounts: [],
      account: '',
      action: '',
      listLoading: false,
      kwInput: '',
      all: false,
      order_by: 'impression',
      order_desc: 1,
      // pagination
      pagesize: 50,
      page: 1,
      total: 0,
      timerange: '',
      data: [],
      form: {
        id: '',
        shopeeaccount_id: '',
        shopeeaccount_account: '',
        id_product: '',
        main_image: '',
        id_ads: '',
        name: '',
        input_promotion_price: 0,
        suppliers: '',
        purchase_cost: 0,
        start_at: '',
        end_at: ''
      },
      innerDialogVisible: false,
      title: '添加广告产品'
    }
  },
  created() {
    this.account = getCookie(SHOPEE_ACCOUNT_ID_KEY)
    this.account = this.account && parseInt(this.account) || ''
    this.handleGetShopeeAccount()
    this.getList()
  },
  methods: {
    handleAdsStatics(row) {
      this.shopeeadsproduct_id = row.id
      this.main_image = row.main_image
      this.ad_link = row.ad_link
      this.id_product = row.id_product
      this.shopeeAdsStaticVisuable = true
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合'
          return
        }
        if (index === 2 || index === 11) {
          sums[index] = 'N/A'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          // 求和
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(1)
        } else {
          sums[index] = 'N/A'
        }
      })
      if (sums[7] > 0) {
        sums[9] = (sums[8] / sums[7]).toFixed(1)
      } else {
        sums[9] = 0
      }

      return sums
    },
    handleAdwordsNote(row) {
      this.shopeeadsproduct_id = row.id
      this.main_image = row.main_image
      this.ad_link = row.ad_link
      this.id_product = row.id_product
      this.shopeeadsoperationnoteVisible = true
    },
    handleShowKeywords(row) {
      this.shopeeadsproduct_id = row.id
      this.main_image = row.main_image
      this.ad_link = row.ad_link
      this.shopeeadskeywordVisible = true
    },
    handleGetShopeeAccount() {
      GetShopeeAccount(null).then((response) => {
        this.accounts = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    resetTemp() {
      this.form = {
        id: '',
        shopeeaccount_id: '',
        shopeeaccount_account: '',
        id_product: '',
        main_image: '',
        id_ads: '',
        name: '',
        input_promotion_price: 0,
        suppliers: '',
        purchase_cost: 0,
        start_at: '',
        end_at: ''
      }
    },
    onSubmit() {
      Post(this.form).then((response) => {
        this.form.account = ''
        this.innerDialogVisible = false
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    getList() {
      this.listLoading = true
      setCookie(SHOPEE_ACCOUNT_ID_KEY, this.account)
      Get(null,
        qs.stringify({
          kw: this.kwInput,
          all: this.all,
          account: this.account,
          days7: 1,
          pagesize: this.pagesize,
          page: this.page,
          order_by: this.order_by,
          order_desc: this.order_desc
        })).then((response) => {
        this.data = response.data.data
        this.total = response.data.total
        this.listLoading = false
        this.$nextTick(() => {
          this.$refs['table'].doLayout()
        })
      }).catch(error => {
        console.log(error)
        this.listLoading = false
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '增加新广告产品'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除 ${row.id_product}?`
          this.form = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改广告产品 ${row.id_product}`
          this.form = Object.assign({}, row)
          console.log(this.form, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.form
      switch (this.action) {
        case 'create':
          Post(this.form
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    }
  }

}
</script>

<style scoped>
table, tr {
  border-color: black;
}

.el-header {
  height: 120px;
  margin-top: 10px;
}

.el-header, .el-footer {
  color: white;
}

.demo-table-expand.el-form-item {
  margin-bottom: 0px;
}
</style>
